package demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-07
 * Time: 8:13
 */

class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
             this.left = left;
             this.right = right;
        }
  }

class Solution {

    private int height(TreeNode root){
        if(root==null) return 0;
        int leftL = height(root.left);
        int rightL = height(root.right);
        if(leftL>=0&&rightL>=0&&Math.abs(leftL-rightL)<=1){
            return 1;
        }
        return -1;
    }

    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        return height(root)>=0;
    }
}
public class Test {

    public static void main(String[] args) {
        Solution solution = new Solution();
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(2);
        TreeNode node4 = new TreeNode(3);
        TreeNode node5 = new TreeNode(3);
        TreeNode node6 = new TreeNode(4);
        TreeNode node7 = new TreeNode(4);
        node1.left =node2;
        node1.right = node3;
        node2.left = node4;
        node4.left = node6;
        node3.right = node5;
        node5.right = node7;
        solution.isBalanced(node1);
    }

}
